package com.d3works.apps.tool.service;

import com.d3works.inject.Beans;
import com.d3works.meta.MetaFiles;
import com.d3works.meta.db.MetaFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Objects;

public class ConvertBinaryToMetafileServiceImpl implements ConvertBinaryToMetafileService {

  public MetaFile convertByteTabPictureInMetafile(byte[] bytePicture) throws IOException {
    Objects.requireNonNull(bytePicture);
    String base64Img = new String(bytePicture);
    String base64ImgData = "";
    if (base64Img.contains(",")) {
      base64ImgData = base64Img.split(",")[1];
    }
    byte[] img = Base64.getDecoder().decode(base64ImgData);
    try (ByteArrayInputStream inImg = new ByteArrayInputStream(img)) {

      return Beans.get(MetaFiles.class)
          .upload(inImg, Files.createTempFile(null, null).toFile().getName());
    }
  }
}
